import { useState, useEffect, useRef } from 'react';
import { Box, Typography, Card, CardContent, Button, Snackbar, Alert, CircularProgress } from '@mui/material';
import { CloudUpload as UploadIcon, GetApp as DownloadIcon, Inbox as InboxIcon } from '@mui/icons-material';
import Breadcrumb, { BreadcrumbItem } from '../../components/Breadcrumb';
import { getImportOptions, downloadTemplate, importFile, ImportOption } from '../../api/import';

// 面包屑导航配置
const breadcrumbItems: BreadcrumbItem[] = [{ title: '首页' }, { title: '信息导入管理' }];

const ImportManagement = () => {
    // 导入选项列表
    const [importOptions, setImportOptions] = useState<ImportOption[]>([]);

    // 页面加载状态
    const [pageLoading, setPageLoading] = useState(true);

    // 导入按钮加载状态
    const [loading, setLoading] = useState<Record<string, boolean>>({});

    // 下载按钮加载状态
    const [downloadLoading, setDownloadLoading] = useState<Record<string, boolean>>({});

    // 错误信息
    const [error, setError] = useState<string | null>(null);

    // 文件输入引用
    const fileInputRefs = useRef<Record<string, HTMLInputElement | null>>({});

    // Snackbar状态
    const [snackbarOpen, setSnackbarOpen] = useState(false);
    const [snackbarMessage, setSnackbarMessage] = useState('');
    const [snackbarSeverity, setSnackbarSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('info');

    // 获取导入选项列表
    useEffect(() => {
        const fetchImportOptions = async () => {
            try {
                setPageLoading(true);
                setError(null);

                // 调用API获取导入选项列表
                const options = await getImportOptions();
                setImportOptions(options);
            } catch (error) {
                console.error('获取导入选项列表失败:', error);
                setError('获取导入选项列表失败，请刷新页面重试');

                // 显示错误提示
                setSnackbarSeverity('error');
                setSnackbarMessage('获取导入选项列表失败，请刷新页面重试');
                setSnackbarOpen(true);
            } finally {
                setPageLoading(false);
            }
        };

        fetchImportOptions();
    }, []);

    // 处理模板下载
    const handleDownloadTemplate = async (option: ImportOption) => {
        try {
            // 设置加载状态
            setDownloadLoading((prev) => ({ ...prev, [option.import_id]: true }));

            // 显示下载中提示
            setSnackbarSeverity('info');
            setSnackbarMessage('正在准备下载模板...');
            setSnackbarOpen(true);

            // 调用下载函数
            await downloadTemplate({
                import_id: option.import_id,
                import_desc: option.import_desc
            });

            // 显示成功提示
            setSnackbarSeverity('success');
            setSnackbarMessage('模板下载成功');
            setSnackbarOpen(true);
        } catch (error) {
            console.error(`下载${option.import_desc}模板失败:`, error);
            setSnackbarSeverity('error');
            setSnackbarMessage('模板下载失败，请稍后重试');
            setSnackbarOpen(true);
        } finally {
            // 清除加载状态
            setDownloadLoading((prev) => ({ ...prev, [option.import_id]: false }));
        }
    };

    // 处理文件选择
    const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>, option: ImportOption) => {
        const files = event.target.files;
        if (!files || files.length === 0) return;

        const file = files[0];
        console.log('选择的文件:', file.name);

        // 验证文件类型
        const fileExtension = file.name.split('.').pop()?.toLowerCase();
        if (fileExtension !== 'xlsx') {
            setSnackbarSeverity('error');
            setSnackbarMessage('文件类型不支持，请选择Excel文件(.xlsx格式)');
            setSnackbarOpen(true);
            event.target.value = '';
            return;
        }

        // 设置加载状态
        setLoading((prev) => ({ ...prev, [option.import_id]: true }));

        // 显示上传中提示
        setSnackbarSeverity('info');
        setSnackbarMessage('正在导入文件...');
        setSnackbarOpen(true);

        try {
            // 获取当前登录用户ID
            const userInfo = localStorage.getItem('userInfo');
            let uid = '';

            if (userInfo) {
                try {
                    const parsedUserInfo = JSON.parse(userInfo);
                    uid = parsedUserInfo.uid || '';
                } catch (e) {
                    console.error('解析用户信息失败:', e);
                }
            }

            // 调用导入函数
            await importFile({
                uid,
                import_id: option.import_id,
                import_desc: option.import_desc,
                file
            });

            // 显示成功提示
            setSnackbarSeverity('success');
            setSnackbarMessage(`${option.import_desc}导入成功`);
            setSnackbarOpen(true);
        } catch (error) {
            console.error(`导入${option.import_desc}失败:`, error);
            setSnackbarSeverity('error');
            setSnackbarMessage('导入失败，请稍后重试');
            setSnackbarOpen(true);
        } finally {
            // 清除加载状态
            setLoading((prev) => ({ ...prev, [option.import_id]: false }));
            // 重置文件输入，允许选择相同文件
            event.target.value = '';
        }
    };

    // 处理导入按钮点击
    const handleImport = (option: ImportOption) => {
        // 如果已经在导入中，不允许再次点击
        if (loading[option.import_id]) return;

        // 触发文件选择框
        fileInputRefs.current[option.import_id]?.click();
    };

    // 处理Snackbar关闭
    const handleSnackbarClose = (_event?: React.SyntheticEvent | Event, reason?: string) => {
        if (reason === 'clickaway') {
            return;
        }
        setSnackbarOpen(false);
    };

    return (
        <Box sx={{ maxWidth: '1200px' }}>
            {/* 隐藏的文件输入框 */}
            {importOptions.map((option) => (
                <input
                    key={`file-input-${option.import_id}`}
                    type="file"
                    ref={(el) => (fileInputRefs.current[option.import_id] = el)}
                    onChange={(e) => handleFileChange(e, option)}
                    accept=".xlsx"
                    style={{ display: 'none' }}
                />
            ))}

            {/* 面包屑导航 */}
            <Box sx={{ mb: 3 }}>
                <Breadcrumb items={breadcrumbItems} />
            </Box>

            {/* 页面标题 */}
            <Box sx={{ mb: 4 }}>
                <Typography
                    variant="h4"
                    component="h1"
                    gutterBottom
                    sx={{
                        fontWeight: 'bold',
                        color: '#333',
                        mb: 1.5
                    }}>
                    信息导入管理
                </Typography>
                <Typography variant="body1" color="text.secondary" sx={{ mb: 1 }}>
                    在此页面可以下载导入模板并导入各类学生信息，支持的文件格式为Excel(.xlsx)
                </Typography>
            </Box>

            {/* 页面加载状态 */}
            {pageLoading ? (
                <Box sx={{ display: 'flex', justifyContent: 'center', my: 8 }}>
                    <CircularProgress size={60} />
                </Box>
            ) : error ? (
                <Alert severity="error" sx={{ my: 2 }}>
                    {error}
                </Alert>
            ) : importOptions.length === 0 ? (
                /* 空状态 */
                <Box
                    sx={{
                        display: 'flex',
                        flexDirection: 'column',
                        alignItems: 'center',
                        justifyContent: 'center',
                        py: 8,
                        px: 2,
                        backgroundColor: '#f9f9f9',
                        borderRadius: '8px',
                        border: '1px dashed #ccc'
                    }}>
                    <InboxIcon
                        sx={{
                            width: '80px',
                            height: '80px',
                            opacity: 0.6,
                            mb: 2,
                            color: '#999'
                        }}
                    />
                    <Typography variant="h6" color="text.secondary" sx={{ mb: 1 }}>
                        暂无可导入的数据
                    </Typography>
                </Box>
            ) : (
                /* 导入选项卡片 */
                <Box
                    sx={{
                        display: 'flex',
                        flexWrap: 'wrap',
                        gap: 3,
                        mt: 2
                    }}>
                    {importOptions.map((option) => (
                        <Box
                            key={option.import_id}
                            sx={{
                                width: { xs: '100%', sm: 'calc(50% - 12px)' },
                                minHeight: '180px',
                                display: 'flex'
                            }}>
                            <Card
                                variant="outlined"
                                sx={{
                                    width: '100%',
                                    display: 'flex',
                                    flexDirection: 'column',
                                    borderRadius: '8px',
                                    overflow: 'hidden',
                                    transition: 'transform 0.2s, box-shadow 0.2s',
                                    '&:hover': {
                                        transform: 'translateY(-4px)',
                                        boxShadow: '0 8px 16px rgba(0,0,0,0.1)'
                                    }
                                }}>
                                <CardContent
                                    sx={{
                                        flexGrow: 1,
                                        display: 'flex',
                                        flexDirection: 'column',
                                        p: 3
                                    }}>
                                    <Typography
                                        variant="h6"
                                        component="h2"
                                        gutterBottom
                                        sx={{
                                            fontWeight: 'bold',
                                            color: '#333',
                                            mb: 1.5
                                        }}>
                                        {option.import_desc}
                                    </Typography>
                                    <Box sx={{ display: 'flex', gap: 2, mt: 'auto' }}>
                                        <Button
                                            variant="outlined"
                                            color="primary"
                                            startIcon={
                                                downloadLoading[option.import_id] ? (
                                                    <CircularProgress size={20} color="inherit" />
                                                ) : (
                                                    <DownloadIcon />
                                                )
                                            }
                                            onClick={() => handleDownloadTemplate(option)}
                                            disabled={downloadLoading[option.import_id]}
                                            sx={{
                                                flex: 1,
                                                py: 1,
                                                borderRadius: '4px'
                                            }}>
                                            {downloadLoading[option.import_id] ? '下载中...' : '下载模板'}
                                        </Button>
                                        <Button
                                            variant="contained"
                                            color="primary"
                                            startIcon={
                                                loading[option.import_id] ? (
                                                    <CircularProgress size={20} color="inherit" />
                                                ) : (
                                                    <UploadIcon />
                                                )
                                            }
                                            onClick={() => handleImport(option)}
                                            disabled={loading[option.import_id]}
                                            sx={{
                                                flex: 1,
                                                py: 1,
                                                borderRadius: '4px'
                                            }}>
                                            {loading[option.import_id] ? '导入中...' : '导入'}
                                        </Button>
                                    </Box>
                                </CardContent>
                            </Card>
                        </Box>
                    ))}
                </Box>
            )}

            {/* Snackbar提示 */}
            <Snackbar open={snackbarOpen} autoHideDuration={6000} onClose={handleSnackbarClose}>
                <Alert onClose={handleSnackbarClose} severity={snackbarSeverity} sx={{ width: '100%' }}>
                    {snackbarMessage}
                </Alert>
            </Snackbar>
        </Box>
    );
};

export default ImportManagement;
